<template>
  <div>
    <el-card class = "box-card">
      <el-row :gutter = "20">
        <el-form ref = "form" label-width = "80px">
          <el-col :span = "6">
            <div class = "grid-content bg-purple">
              <el-input v-model = "queryParameter.username" placeholder = "请根据用户名搜索"></el-input>
            </div>
          </el-col>
        </el-form>
        <el-col :span = "4">
          <div class = "grid-content bg-purple">
            <el-button @click = "clearSearchResults">清除</el-button>
            <el-button @click = "getUsersList" type = "primary">搜索</el-button>
          </div>
        </el-col>
        <el-col :offset = "11" :span = "2">
          <div class = "grid-content bg-purple">
            <el-button icon = "el-icon-edit" type = "success" @click = "addDialogVisible=true">新建用户</el-button>
          </div>
        </el-col>
      </el-row>
      <template>
        <el-alert style = "margin: 10px 0" :title = "`数据一共 ${10} 条`" type = "info" show-icon
                  :closable = "false"></el-alert>
      </template>
      <div>
        <template>
          <el-table ref = "singleTable" :data = "usersList" highlight-current-row style = "width: 100%">
            <el-table-column align = "center" prop = "id" type = "index" label = "序号" width = "100"></el-table-column>
            <el-table-column align = "center" prop = "email" label = "邮箱"></el-table-column>
            <el-table-column align = "center" prop = "phone" label = "联系电话" width = "200"></el-table-column>
            <el-table-column align = "center" prop = "username" label = "用户名" width = "200"></el-table-column>
            <el-table-column align = "center" prop = "permission_group_title" label = "权限组名称"
                             width = "200"></el-table-column>
            <el-table-column align = "center" prop = "role" label = "角色" width = "200"></el-table-column>
            <el-table-column align = "center" prop = "" label = "操作" width = "200">
              <template slot-scope = "scope">
                <el-button type = "primary" plain icon = "el-icon-edit" circle @click="getEditUserInfo(scope.row)"></el-button>
                <el-button type = "danger" plain icon = "el-icon-delete" circle v-if = "scope.row.role!=='admin'"
                           @click = "delUser(scope.row)"></el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <div class = "block" style = "margin:20px;float: right">
        <el-pagination
          background
          @size-change = "handleSizeChange"
          @current-change = "handleCurrentChange"
          :current-page = "queryParameter.page"
          :page-sizes = "[5, 10, 20, 50]"
          :page-size = "queryParameter.pagesize"
          layout = "prev, pager, next,sizes,jumper"
          :total = "counts">
        </el-pagination>
      </div>
    </el-card>
    <!--    添加用户对话框-->
    <el-dialog
      title = "创建用户"
      :visible.sync = "addDialogVisible"
      width = "30%">
      <user-add :options = "options" @onUsersParameter = "getUserParameter"></user-add>
      <span slot = "footer" class = "dialog-footer">
    <el-button @click = "addDialogVisible = false">取 消</el-button>
    <el-button type = "primary" @click = "addUser">确 定</el-button>
  </span>
    </el-dialog>
    <!--    修改用户对话框-->
    <el-dialog
      title = "编辑用户"
      :visible.sync = "editDialogVisible"
      width = "30%">
      <div>
      <el-form ref="form" :model="editUserParameter" label-width="100px" :rules="addFromRules">
        <el-form-item label="用户名">
          <el-input v-model="editUserParameter.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editUserParameter.email"></el-input>
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="editUserParameter.role"></el-input>
        </el-form-item>
        <el-form-item label="权限组名称">
          <el-select v-model="editUserParameter.permission_group_id" placeholder="请选择">
            <el-option v-for="item in options" :key="item.id" :label="item.title" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editUserParameter.phone"></el-input>
        </el-form-item>
        <el-form-item label="介绍">
          <el-input type="textarea" v-model="editUserParameter.introduction"></el-input>
        </el-form-item>
      </el-form>
      </div>
      <span slot = "footer" class = "dialog-footer">
    <el-button @click = "editDialogVisible = false">取 消</el-button>
    <el-button type = "primary" @click = "editUser">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import * as Users from '@/api/base/users'
import * as Permissions from '@/api/base/permissions'
import UserAdd from '@/module-manage/components/user-add'

export default {
  components: {
    UserAdd
  },
  data () {
    // 邮箱校验规则
    const checkEmail = function (rule, value, cb) {
      const reg = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-z]{2,}$/
      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('邮箱格式不对'))
      }
    }
    // 手机号校验规则
    const checkMobile = function (rule, value, cb) {
      const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|16[6]|19[89]]|17[01345678]|18[0-9]|14[579])[0-9]{8}$/
      if (reg.test(value)) {
        cb()
      } else {
        cb(new Error('手机格式不对'))
      }
    }
    return {
      // 请求参数
      queryParameter: {
        page: 1,
        pagesize: 10,
        keyword: '',
        disabled: '',
        username: ''
      },
      usersList: [], // 用户列表
      counts: null, // 用户数
      addDialogVisible: false, // 添加对话框默认隐藏
      options: [], // 权限组信息
      usersParameter: {}, // 添加的用户信息
      editDialogVisible: false, // 编辑对话框默认隐藏
      // 编辑的用户信息
      editUserParameter: {},
      // 用户信息表单验证
      addFromRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 5, max: 25, message: '长度在 5 到 25个字符', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ],
        role: [{ required: true, message: '请输入角色名', trigger: 'blur' }]
      }
    }
  },

  created () {
    this.getUsersList()
    this.getPermission()
  },

  methods: {
    // 获取用户列表
    async getUsersList () {
      try {
        const { data: res } = await Users.list(this.queryParameter)
        console.log('用户列表', res)
        this.usersList = res.list
        this.counts = res.counts
      } catch (err) {
        console.log(err)
      }
    },
    // 分页
    handleSizeChange (pagesize) {
      this.queryParameter.pagesize = pagesize
      this.getUsersList()
    },
    handleCurrentChange (page) {
      this.queryParameter.page = page
      this.getUsersList()
    },
    // 清除搜索结果
    async clearSearchResults () {
      this.queryParameter.username = ''
      await this.getUsersList()
    },
    // 获取权限组信息
    async getPermission () {
      const { data: res } = await Permissions.list(this.queryParameter)
      // console.log('权限组信息', res)
      this.options = res.list
    },
    // 获取子组件用户添加信息
    getUserParameter (usersParameter) {
      this.usersParameter = usersParameter
    },
    // 添加用户
    async addUser () {
      try {
        console.log(this.usersParameter)
        const { data: res } = await Users.add(this.usersParameter)
        console.log(res)
        this.addDialogVisible = false
        this.$message.success('添加成功')
        await this.getUsersList()
      } catch (err) {
        console.log(err)
        this.$message.error('添加失败')
      }
    },
    // 删除用户
    async delUser (row) {
      const confirmResult = await this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      try {
        const { data: res } = await Users.remove(row)
        console.log(res)
        this.$message.success('删除成功')
        await this.getUsersList()
      } catch (error) {
        this.$message.error('删除失败!')
      }
    },
    // 获取修改用户的信息
    async getEditUserInfo (row) {
      this.editDialogVisible = true
      const { data } = await Users.detail(row)
      console.log(data)
      this.editUserParameter = data
    },
    // 修改用户
    async editUser () {
      try {
        await Users.update(this.editUserParameter)
        this.$message.success('修改成功')
        this.editDialogVisible = false
        await this.getUsersList()
      } catch (err) {
        this.$message.error('修改失败')
      }
    }
  }
}
</script>

<style scoped lang = 'less'>

</style>
